// QuestionViewRecordList.tsx
import React, { useState, useEffect } from "react";
import {
  List,
  Card,
  Tag,
  Typography,
  Empty,
  Spin,
  Button,
  Pagination,
} from "antd";
import { RedoOutlined } from "@ant-design/icons";
import { getUserQuestionViewListUsingGet } from "@/api/userController";
import UserQuestionViewVO = API.UserQuestionViewVO;
import Link from "next/link";

const { Text, Title } = Typography;

interface QuestionViewRecordListProps {
  refreshTrigger?: number; // 添加刷新触发器
  onRefresh?: () => void; // 添加刷新回调
}

const QuestionViewRecordList: React.FC<QuestionViewRecordListProps>= ({refreshTrigger,onRefresh}) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<UserQuestionViewVO[]>([]);
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const pageSize = 10;

  const loadData = async (page: number = 1) => {
    setLoading(true);
    try {
      const res = await getUserQuestionViewListUsingGet({
        current: page,
        size: pageSize,
      });
      if (res.code === 0 && res.data) {
        setData(res.data.records || []);
        setTotal(res.data.total || 0);
        setCurrent(page);
      }
    } catch (error) {
      console.error("获取浏览记录失败:", error);
    } finally {
      setLoading(false);
    }
  };

  // //添加刷新函数
  // const handleRefresh = () => {
  //   loadData(1);
  //   if (onRefresh) {
  //     onRefresh();
  //   }
  // };

  useEffect(() => {
    loadData(1);
  }, [refreshTrigger]); // 监听refreshTrigger变化

  // 添加实时刷新功能 - 每30秒自动刷新一次
  // useEffect(() => {
  //   const interval = setInterval(() => {
  //     loadData(current);
  //   }, 30000); // 30秒刷新一次
  //
  //   return () => clearInterval(interval);
  // }, [current]);

  const formatDate = (dateString?: string) => {
    if (!dateString) return "";
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  if (loading && data.length === 0) {
    return (
      <div style={{ textAlign: "center", padding: "40px 0" }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <Card
      title={
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <span>题目浏览记录</span>
          {/*<Button*/}
          {/*  icon={<RedoOutlined />}*/}
          {/*  size="small"*/}
          {/*  onClick={handleRefresh}*/}
          {/*  loading={loading}*/}
          {/*>*/}
          {/*  刷新*/}
          {/*</Button>*/}
        </div>
      }
      style={{ marginTop: 16 }}
    >
      {data.length === 0 ? (
        <Empty description="暂无浏览记录" />
      ) : (
        <>
          <List
            dataSource={data}
            renderItem={(item) => (
              <List.Item>
                <div style={{ width: "100%" }}>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "flex-start",
                      marginBottom: 8,
                    }}
                  >
                    <Title level={5} style={{ margin: 0, flex: 1 }}>
                        <Link href={`/question/${item.questionId}`}>
                            {item.questionTitle || "未知题目"}
                        </Link>
                    </Title>
                    <Tag color="blue">{item.viewCount}次浏览</Tag>
                  </div>

                  {item.questionContent && (
                    <Text type="secondary" ellipsis={{ rows: 2 }}>
                      {item.questionContent}
                    </Text>
                  )}

                  <div style={{ marginTop: 8, color: "#999", fontSize: 12 }}>
                    最后浏览时间: {formatDate(item.viewTime || item.createTime)}
                  </div>
                </div>
              </List.Item>
            )}
          />

          {total > pageSize && (
            <div style={{ textAlign: "right", marginTop: 16 }}>
              <Pagination
                current={current}
                pageSize={pageSize}
                total={total}
                onChange={loadData}
                size="small"
              />
            </div>
          )}
        </>
      )}
    </Card>
  );
};

export default QuestionViewRecordList;
